package com.atguigu.gmall.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.common.utils.IPUtil;
import com.atguigu.gmall.common.constant.GmallConstant;
import com.atguigu.gmall.common.execption.GmallException;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.user.dto.UserLoginDto;
import com.atguigu.gmall.user.vo.UserLoginSuccessVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gmall.user.entity.UserInfo;
import com.atguigu.gmall.user.service.UserInfoService;
import com.atguigu.gmall.user.mapper.UserInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.UUID;

/**
* @author xueyoupeng
* @description 针对表【user_info(用户表)】的数据库操作Service实现
* @createDate 2023-07-24 22:48:06
*/
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService{

    @Autowired
    private UserInfoMapper userInfoMapper ;

    @Autowired
    private RedisTemplate<String , String> redisTemplate ;

    @Override
    public UserLoginSuccessVo login(UserLoginDto userLoginDto) {

        // 根据用户名查询数据库
        LambdaQueryWrapper<UserInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //根据用户名来查询 具体参数是userLoginDto里面的loginName
        lambdaQueryWrapper.eq(UserInfo::getLoginName , userLoginDto.getLoginName());
        UserInfo userInfo = userInfoMapper.selectOne(lambdaQueryWrapper);
        if (userInfo == null){
            throw new GmallException(ResultCodeEnum.LOGIN_ERROR);
        }

        //判断密码
        String passwd = userLoginDto.getPasswd();
        //把密码转成字节数组
        String md5Passwd = DigestUtils.md5DigestAsHex(passwd.getBytes());
        if (!md5Passwd.equals(userInfo.getPasswd())){
            throw new GmallException(ResultCodeEnum.LOGIN_ERROR) ;
        }

        //密码正确 生成令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        //存储到redis中的键和值
        redisTemplate.opsForValue().set(GmallConstant.REDIS_USER_LOGIN_PRE + token , JSON.toJSONString(userInfo));

        //构建相应结果数据
        UserLoginSuccessVo userLoginSuccessVo = new UserLoginSuccessVo();
        userLoginSuccessVo.setToken(token);
        userLoginSuccessVo.setNickName(userInfo.getNickName());

        return userLoginSuccessVo;
    }

    @Override
    public void logout(String token) {
        redisTemplate.delete(GmallConstant.REDIS_USER_LOGIN_PRE + token);
    }
}




